package com.infindo.frame.util;

import java.util.Stack;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.util.Log;

 
 

public class ScreenManager {
	
	private static final String TAG = "ScreenManager";
	
	private static Stack<Activity> activityStack;
	private static ScreenManager instance;

	private ScreenManager() {
	}

	public static ScreenManager getScreenManager() {
		if (instance == null) {
			instance = new ScreenManager();
		}
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		return instance;
	}



	public void popActivity(Activity activity) {
		if (activity != null) {
			activity.finish();
			activityStack.remove(activity);
			activity = null;
		}
	}

	public Activity currentActivity() {
		try {
			Activity activity = activityStack.lastElement();
			return activity;
		} catch (Exception e) {
			return null;
		}

	}
	
	public int getActivitySize(){
		if(activityStack == null)
			return 0;
		return activityStack.size();
	}

	public void pushActivity(Activity activity) {

		activityStack.add(activity);
	}
	

	public void popAllActivityExceptOne(Class<?> cls) {
		while (true) {
			Activity activity = currentActivity();
			if (activity == null) {
				break;
			}
//			Log.e(TAG,"activitySize:"+getActivitySize());
			if (activity.getClass().equals(cls) && getActivitySize()<=1) {
				break;
			}
			popActivity(activity);
		}
	}
	
	public void popAllActivityExceptOneAndMe(Class<?> cls,Activity me) {
		int index = 0;
		while (activityStack.size()>index) {
			Activity activity = activityStack.lastElement();
			if (activity == null) {
				break;
			}
			if (activity.getClass().equals(cls)) {
				break;
			}
			if(!activity.equals(me)){
				activityStack.remove(activity);
			}
			index++;
		}
//		pushActivity(me);
	}
	
	public void popAllActivityAddMe(Activity activity) {
		while (true) {
			Activity a = currentActivity();
			if (a == null) {
				break;
			}
			if(!activity.equals(a))
			   popActivity(a);
			else
				activityStack.remove(activity);
		}
		pushActivity(activity);
		
	}
	
	public void popAllActivity() {
		while (true) {
			Activity a = currentActivity();
			if (a == null) {
				break;
			}
			popActivity(a);

		}
		activityStack.removeAllElements();
		activityStack.clear();
	}
	
	public static String showMemory(Context context) {
		if (null == context) {
		return "0k";
		}
		ActivityManager am =
		(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
		am.getMemoryInfo(outInfo);

		return outInfo.availMem/1024+"k";
   }
	
}
